import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:logmanager/utils/string_ext.dart';
import 'package:flutter/material.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';

import '../../bean/user.dart';
import '../../bean/user_bean.dart';
import '../../common/account_config.dart';
import '../../routers/router.dart';
import 'login_provider.dart';

class LoginController extends GetxController {
  LoginProvider loginProvider = Get.put(LoginProvider());

  /// 发送验证码按钮是否可点击
  var btnCodeEnabled = true.obs;

  /// 登录按钮是否可点击
  var btnLoginEnabled = true.obs;
  final codeFocusNode = FocusNode();
  TextEditingController? _phoneController;
  TextEditingController? _codeController;
  var checked = true.obs;

  @override
  void onInit() {
    _initHxSDK();
    super.onInit();
  }

  void setLoginEnabled({
    String? phoneStr,
    String? codeStr,
    String? passwordStr,
  }) {
    btnLoginEnabled.value = (phoneStr?.length == 13) && (codeStr?.length == 4);
  }

  void login(String mobile, String? code) async {
    btnLoginEnabled.value = false;
    // 执行网络请求
    loginProvider.login(
      mobile.replaceAll(" ", ""),
      code,
      success: (value) {
        User.setToken(value.token);
        UserBean userBean = value.assistants;
        User.setUserName(userBean.name ?? "");
        User.setUserPhone(userBean.mobile ?? "");
        User.setHXName(userBean.hxUsername ?? "");
        User.setHXPasswd(userBean.hxPassword ?? "");
        btnLoginEnabled.value = true;
        // change(value, status: RxStatus.success());
        // jumpToHome();
        "fdasfasd${userBean.hxUsername}----${userBean.hxPassword}".toast();
        loginHx(userBean.hxUsername??"", userBean.hxPassword??"");
      },
      fail: (value) {
        btnLoginEnabled.value = true;
      },
    );
  }

  void loginHx(String hxName,String hxPassword) async {
    try {
      await EMClient.getInstance.loginWithPassword(hxName, hxPassword);
      "登陆成功".toast();
      Get.offNamed(Routes.homePage);
    } on EMError catch (e) {
      "登陆失败, e: ${e.code} , ${e.description}".toast();
    }
  }

  void _initHxSDK() async {
    EMOptions options = EMOptions.withAppKey(
      AccountConfig.HX_KEY,
      autoLogin: false,
      debugMode: true
    );
    await EMClient.getInstance.init(options);
    // 通知 SDK UI 已准备好。该方法执行后才会收到 `EMChatRoomEventHandler`、`EMContactEventHandler` 和 `EMGroupEventHandler` 回调。
    await EMClient.getInstance.startCallback();
  }
}
